#pragma once
#include"Eventloop.h"
#include"Socket.h"
#include"Acceptor.h"
#include"InetAddress.h"
#include"noncopyable.h"
#include"TcpConnection.h"
#include"Callbacks.h"
#include"Buffer.h"
#include"EventloopThreadPool.h"

#include<functional>
#include<string>
#include<memory>
#include<atomic>
#include<unordered_map>
//对外的服务编程所使用的类
class Tcpserver
{
    public:
        using ThreadInitCallback=std::function<void(Eventloop*)>;
        enum Option
        {
            kNoReusePort,
            kReusePort,
        };
        Tcpserver(Eventloop *loop,
                  const InetAddress &listenAddr,
                  const std::string &nameArgs,
                  Option option=kNoReusePort);
        ~Tcpserver();
        void setConnectionCallback(const ConnectionCallback &cb){connectionCallback_=cb;}
        void setWriteCompleteCallback(const WriteCompleteCallback &cb){writeCompleteCallback_=cb;}
        void setMessageCallback(const MessageCallback &cb){messageCallback_=cb;}
        void setThreadInitcallback(const ThreadInitCallback &cb) {threadInitCallback_=cb;}
        void setThreadNum(int numThreads); //设置subloop的个数
        void start();//开启服务器监听
    private:
        void newConnection(int sockfd,const InetAddress &peerAddr);
        void removeConnection(const TcpConnectionPtr &conn);
        void removeConnectionInLoop(const TcpConnectionPtr &conn);
        using ConnectionMap=std::unordered_map<std::string,TcpConnectionPtr>;
        Eventloop *loop_;
        const std::string ipPort_;
        const std::string name_;
        std::unique_ptr<Acceptor> acceptor_;//运行在main loop主要是监听新连接事件
        std::shared_ptr<EventloopThreadPool> threadPool_;
        ConnectionCallback connectionCallback_;//有新连接时候的回调
        MessageCallback messageCallback_;//有读写消息时候的回调
        WriteCompleteCallback writeCompleteCallback_;//消息发送完之后的回调
        ThreadInitCallback threadInitCallback_;//loop线程初始化之后的回调

        std::atomic_int started_;
        int nextConnId_;
        ConnectionMap connections_;//保存所有的连接


};